package ltd.newbee.mall.api.mall;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.api.mall.vo.RspObjBean;
import ltd.newbee.mall.service.AccessTokenService;
import ltd.newbee.mall.util.Base64Utils;
import nuonuo.open.sdk.NNOpenSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.UUID;

@Slf4j
@Api(value = "发票接口", description = "发票接口")
@RestController
@RequestMapping("/api/v1")
public class BillContorller {


    @Autowired
    private AccessTokenService accessTokenService;
    @Value("${bill.appKey}")
    public String appKey;
    @Value("${bill.appSecret}")
    public String appSecret;
    @Value("${bill.url}")
    public String url;
    @Value("${bill.taxnum}")
    public String taxnum;
    private Logger logger = LoggerFactory.getLogger(BillContorller.class);





    @ApiOperation("查询开具发票接口")
    @RequestMapping(value = "/getBill", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "{\n" +
                    "\t\"isOfferInvoiceDetail\": \"1\",\n" +
                    "\t\"orderNos\": [],\n" +
                    "\t\"serialNos\": [\n" +
                    "\t\t\"21122909311802027307\"\n" +
                    "\t]\n" +
                    "}", paramType = "query", dataType = "String", required = true),
    })
    public @ResponseBody
    RspObjBean getBill(String content) {
        logger.info("查询开具发票接口<>=" + content);
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        logger.info("测试查询开具发票接口=NNOpenSDK");
        String method = "nuonuo.ElectronInvoice.queryInvoiceResult"; // API方法名
        String token = accessTokenService.getMaxAccessToken(sdk); // 访问令牌
        logger.info("查询开具发票接口token<>=" + token);
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        logger.info(result);
        RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
        });
        //只有成功才会翻译图片pdfUrl
        if ("E0000".equals(rspObjBean.getCode())) {
            JSONArray jsonArray = JSON.parseArray(rspObjBean.getResult().toString());
            // 遍历JSONArray
            for (Iterator<Object> iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                JSONObject jsonObject = (JSONObject) iterator.next();
                jsonObject.put("imgBase64", Base64Utils.ImageToBase64ByOnline(jsonObject.getString("pdfUrl")));
                logger.info("base64结果<>=" + jsonObject.getString("imgBase64").substring(0, 20));
                //System.out.println(jsonObject.getString("imgBase64"));
            }
            rspObjBean.setResult(jsonArray);
        }
        return rspObjBean;
    }


    @ApiOperation("开具发票重试接口")
    @RequestMapping(value = "/reBill", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "{\n" +
                    "\t\"fpqqlsh\": \"21122909311802027307\",\n" +
                    "\t\"orderno\": \"1231231\"\n" +
                    "}", paramType = "query", dataType = "String", required = true),
    })
    public @ResponseBody
    RspObjBean reBill(String content) {
        logger.info("开具发票重试接口<>=" + content);
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String method = "nuonuo.ElectronInvoice.reInvoice"; // API方法名
        String token = accessTokenService.getMaxAccessToken(sdk); // 访问令牌
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        logger.info(result);
        RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
        });
        return rspObjBean;
    }

    @ApiOperation("新增开具发票接口")
    @RequestMapping(value = "/newBill2", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "{\n" +
                    "\t\"order\": {\n" +
                    "\t\t\"terminalNumber\": \"\",\n" +
                    "\t\t\"invoiceDetail\": [{\n" +
                    "\t\t\t\"specType\": \"y460\",\n" +
                    "\t\t\t\"taxExcludedAmount\": \"0.88\",\n" +
                    "\t\t\t\"invoiceLineProperty\": \"0\",\n" +
                    "\t\t\t\"favouredPolicyName\": \"0\",\n" +
                    "\t\t\t\"num\": \"1\",\n" +
                    "\t\t\t\"withTaxFlag\": \"1\",\n" +
                    "\t\t\t\"tax\": \"0.12\",\n" +
                    "\t\t\t\"favouredPolicyFlag\": \"0\",\n" +
                    "\t\t\t\"taxRate\": \"0.13\",\n" +
                    "\t\t\t\"unit\": \"台\",\n" +
                    "\t\t\t\"deduction\": \"0\",\n" +
                    "\t\t\t\"price\": \"1\",\n" +
                    "\t\t\t\"zeroRateFlag\": \"0\",\n" +
                    "\t\t\t\"goodsCode\": \"1090511030000000000\",\n" +
                    "\t\t\t\"selfCode\": \"130005426000000000\",\n" +
                    "\t\t\t\"goodsName\": \"电脑\",\n" +
                    "\t\t\t\"taxIncludedAmount\": \"1\"\n" +
                    "\t\t}],\n" +
                    "\t\t\"buyerTel\": \"0571-88888888\",\n" +
                    "\t\t\"listFlag\": \"0\",\n" +
                    "\t\t\"pushMode\": \"1\",\n" +
                    "\t\t\"departmentId\": \"9F7E9439CA8B4C60A2FFF3EA3290B088\",\n" +
                    "\t\t\"clerkId\": \"\",\n" +
                    "\t\t\"remark\": \"备注信息\",\n" +
                    "\t\t\"checker\": \"王五\",\n" +
                    "\t\t\"payee\": \"李四\",\n" +
                    "\t\t\"buyerAddress\": \"杭州市\",\n" +
                    "\t\t\"buyerTaxNum\": \"\",\n" +
                    "\t\t\"invoiceType\": \"1\",\n" +
                    "\t\t\"invoiceLine\": \"p\",\n" +
                    "\t\t\"email\": \"test@xx.com\",\n" +
                    "\t\t\"salerAccount\": \"\",\n" +
                    "\t\t\"salerTel\": \"0571-77777777\",\n" +
                    "\t\t\"orderNo\": \"20170105120207971567\",\n" +
                    "\t\t\"callBackUrl\": \"http:127.0.0.1/invoice/callback/\",\n" +
                    "\t\t\"buyerName\": \"企业名称/个人\",\n" +
                    "\t\t\"invoiceDate\": \"2016-01-13 12:30:00\",\n" +
                    "\t\t\"invoiceCode\": \"125999915630\",\n" +
                    "\t\t\"invoiceNum\": \"00130865\",\n" +
                    "\t\t\"salerAddress\": \"\",\n" +
                    "\t\t\"clerk\": \"张三\",\n" +
                    "\t\t\"buyerPhone\": \"15858585858\",\n" +
                    "\t\t\"buyerAccount\": \"中国工商银行 111111111111\",\n" +
                    "\t\t\"productOilFlag\": \"0\",\n" +
                    "\t\t\"extensionNumber\": \"\",\n" +
                    "\t\t\"salerTaxNum\": \"339901999999516\",\n" +
                    "\t\t\"listName\": \"详见销货清单\",\n" +
                    "\t\t\"proxyInvoiceFlag\": \"0\"\n" +
                    "\t}\n" +
                    "}", paramType = "query", dataType = "String", required = true),
    })
    public @ResponseBody
    RspObjBean newBill2(String content) {
        logger.info("请求开具发票接口<>=" + content);
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        logger.info("测试请求开票执行=NNOpenSDK");
        String method = "nuonuo.ElectronInvoice.requestBillingNew"; // API方法名
        String token = accessTokenService.getMaxAccessToken(sdk); // 访问令牌
        logger.info("请求开具发票接口访问token<>=" + token);
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = sdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        logger.info(result);
        RspObjBean rspObjBean = JSON.parseObject(result, new TypeReference<RspObjBean>() {
        });
        return rspObjBean;
    }



}
